<template>
  <div class="setcoverimg" style="overflow:hidden;margin:20px">
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <el-calendar>
        <template slot="dateCell" slot-scope="{date, data}">
          <div class="dateCell" @click="adddate(data.day)">
            <template v-for="(item,index) in selectedDate">
              <div v-if="item===data.day" :key="item+index" style="float:right">✔️</div>
            </template>
            <div class="calendar-day">{{ data.day.split('-').slice(2).join('-') }}</div>
            <template v-for="(item,index) in calendarData">
              <template v-if="item.date===data.day">
                <div :key="item+index" class="is-selected">
                  <a :href="$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(item.imageId)" target="_blank">
                    <i class="el-icon-picture" />
                  </a>
                </div>
              </template>
            </template>
          </div>
        </template>
      </el-calendar>
      <el-form-item label="日期选择" style="clear:both">
        <el-select v-model="selectedDate" multiple placeholder="请选择" />
      </el-form-item>
      <el-form-item label="封面图片" style="clear:both">
        <el-upload
          class="avatar-uploader"
          :action="this.$http.defaults.baseURL+'api/gen/file/upload/'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :headers="myHeaders"
          accept="image/jpeg,image/png,image/gif"
        >
          <img v-if="imageUrl" :src="this.$http.defaults.baseURL+'api/gen/file/download?id='+parseInt(imageUrl)" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item style="margin-bottom: 30px;">
        <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
const defaultForm = {
  classCode: '',
  content: '', // 文章内容
  files: [], // 文章图片
  id: null,
  isTop: 0,
  publishTime: '', // 前台展示时间
  title: '' // 文章题目
}

export default {
  name: 'ArticleDetail',
  props: {
    signTime: {
      type: String,
      default: ''
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: '请将表单填写完整',
          type: 'error'
        })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      selectedDate: [],
      calendarData: [],
      postForm: Object.assign({}, defaultForm),
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      loading: false,
      classOption: [],
      rules: {
        imageUrl: [{ validator: validateRequire }],
        selectedDate: [{ validator: validateRequire }]
      },
      tempRoute: {},
      selectedId: 0,
      infoType: 0
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        console.log('signTime:' + val)
        this.getData(this.signTime)
      },
      immediate: true
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getData()
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    adddate(date) {
      console.log(date)
      if (this.selectedDate.indexOf(date) === -1) {
        this.selectedDate.push(date)
      } else {
        var key = this.selectedDate.indexOf(date)
        this.selectedDate.splice(key, 1)
      }
    },
    submitForm() {
      if (this.selectedDate && this.selectedDate.length && this.selectedDate.length > 0) {
        if (this.imageUrl && this.imageUrl !== '') {
          const day = new Date()
          day.setTime(day.getTime())
          const para = {
            dateList: this.selectedDate,
            fileId: this.imageUrl
          }
          this.loading = true
          this.$http
            .post('/api/busSignIn/saveSignPic', para)
            .then(response => {
              this.loading = false
              if (response.data.success === true) {
                this.$message({
                  message: '保存成功',
                  type: 'success'
                })
                this.getData()
                this.selectedDate = []
              } else {
                console.log('保存失败:' + response.data.message)
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(function(error) {
              console.log(error)
              this.loading = false
            })
        } else {
          this.$message({
            message: '请上传图片',
            type: 'error'
          })
        }
      } else {
        this.$message({
          message: '请选择日期',
          type: 'error'
        })
      }
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData() {
      this.infoLoading = true
      this.$http
        .get('/api/busSignIn/getAllSignInPicList')
        .then(response => {
          this.infoLoading = false
          if (response.data.success === true) {
            this.calendarData = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
          this.infoLoading = false
        })
    }
  }
}
</script>
<style>
.setcoverimg .el-calendar-table .el-calendar-day .dateCell{
  padding:10px !important;
  height:60px !important;
}
.setcoverimg .el-calendar-table .el-calendar-day{
  padding:0 !important;
  height:60px !important;
  font-size:14px;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.is-selected {
  color: #1989FA;
}
.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
